package net.giafei.tools.demo;

import com.github.shyiko.mysql.binlog.BinaryLogClient;
import com.github.shyiko.mysql.binlog.event.EventData;
import com.github.shyiko.mysql.binlog.event.XidEventData;
import com.github.shyiko.mysql.binlog.event.deserialization.EventDeserializer;

import java.io.IOException;

/**
 * MysqlBinLog
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2021-03-19 14:21
 */
public class MysqlBinLogTest {

    public static void main(String[] args) throws IOException {
//        File file = new File("D:\\Desktop\\logs\\Xshell\\mysql-bin.000183");
//        EventDeserializer eventDeserializer = new EventDeserializer();
//        eventDeserializer.setCompatibilityMode(
//                EventDeserializer.CompatibilityMode.DATE_AND_TIME_AS_LONG,
//                EventDeserializer.CompatibilityMode.CHAR_AND_BINARY_AS_BYTE_ARRAY
//        );
//        int k = 0;
//        try (BinaryLogFileReader reader = new BinaryLogFileReader(file, eventDeserializer)){
//            for (Event event; (event = reader.readEvent()) != null;) {
//                EventData data = event.getData();
//                if(Objects.isNull(data)){
//                    continue;
//                }
//                if(k > 99){
//                    break;
//                }
//                k++;
//                System.out.println(data.toString());
//                if (data.getClass().isAssignableFrom(UpdateRowsEventData.class)) {
//                    UpdateRowsEventData dmlData = (UpdateRowsEventData) data;
//                    System.out.println(dmlData.toString());
//                    continue;
//                }
//                if (data.getClass().isAssignableFrom(RowsQueryEventData.class)) {
//                    RowsQueryEventData dmlData = (RowsQueryEventData) data;
//                    //System.out.println(dmlData.getQuery());
//                    continue;
//                }
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }



        BinaryLogClient client = new BinaryLogClient("192.168.102.213", 3306, "cms", "123456");
        EventDeserializer eventDeserializer = new EventDeserializer();
        eventDeserializer.setCompatibilityMode(
                EventDeserializer.CompatibilityMode.DATE_AND_TIME_AS_LONG,
                EventDeserializer.CompatibilityMode.CHAR_AND_BINARY_AS_BYTE_ARRAY
        );
        client.setEventDeserializer(eventDeserializer);
        client.registerEventListener(event -> {
            System.out.println(event.toString());
            EventData data = event.getData();
            //System.out.println(data.toString());
            if(data instanceof XidEventData){
                System.out.println("---------------------------------------------");
            }
        });
        client.connect();
    }
}
